package com.example.jin.des;

/**
 * Created by Administrator on 2017/12/12.
 */

public class ByteUtil {


    /**
     * 字节数组拼接
     *
     * @param bt1
     * @param bt2
     * @return
     */
    public static byte[] byteContact(byte[] bt1, byte[] bt2) {
        if (bt1 == null) {
            return bt2;
        } else {
            byte[] bt3 = new byte[bt1.length + bt2.length];
            System.arraycopy(bt1, 0, bt3, 0, bt1.length);
            System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
            return bt3;
        }

    }

    /**
     * 16进制数据转字符串格式
     *
     * @param b   需要转换的16进制数据
     * @param len 需要转换的数据长度
     * @return 转换后的字符串
     */
    public  static String HexToString(byte[] b, int len) {
        StringBuilder result = new StringBuilder();
        String hex;
        for (int i = 0; i < len; i++) {
            hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            result.append(hex.toUpperCase());
        }
        return result.toString();
    }

    /**
     * 16进制数据转字符串格式
     *
     * @param b 需要转换的16进制数据
     * @return 转换后的字符串
     */
    public static String HexToString(byte[] b) {
        return HexToString(b, b.length);
    }

    /**
     * 将16进制格式的字符串转换为对应的16进制数据
     *
     * @param src 需要转换的字符串
     * @return 转换后的16进制数据数组
     */
    public static byte[] StringToHex(String src) {
        String str = src.trim();
        int l = str.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = Integer.valueOf(str.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }



}
